import java.util.PriorityQueue;

/**
 * @author hewei
 * @version 1.0
 * @description: 周赛318 t3
 * @date 2022/11/6 10:46
 */

public class TotalCost {

    public static void main(String[] args) {
        Integer a = 127;
        Integer b = 127;
        System.out.println(a == b);
    }

    public long totalCost(int[] costs, int k, int candidates) {
        PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> {
            if (costs[a] != costs[b]) return costs[a] - costs[b];
            return a - b;
        });
        int n = costs.length;
        int l = 0;
        int r = n - 1;
        int i = 0;
        for (; i < candidates; i++) {
            if (l < r) {
                heap.add(l);
                heap.add(r);
            } else {
               if (l == r) heap.add(l);
               break;
            }
            ++l;
            --r;
        }
        if (i == candidates) {
            --l;
            ++r;
        }
        long ans = 0;
        while (k-- > 0) {
            Integer poll = heap.poll();
            ans += costs[poll];
            if (r - l > 1) {
                if (poll <= l) {
                    ++l;
                    heap.add(l);
                } else {
                    --r;
                    heap.add(r);
                }
            }
        }
        return ans;
    }
}
